var util = require('../utils/util');
var daoUtil = require('../utils/daoUtil');
var KnowledgeCenter = require('../class/knowledgecenter');

module.exports = {

    create: function (params, cb) {
        var validate = daoUtil.validate(['content', 'createUid', 'attachmentName','attachmentUrl','knowledgegroup','createUser'], params);
        if(!validate.valid){
            cb(validate.error);
            return;
        }
        var groupIds = params.knowledgegroup;
        if(groupIds.length > 0){
            if(groupIds.length ==2 && groupIds[1] !=''){
                params.knowledgegroup = groupIds[1];
            }else{
                params.knowledgegroup = groupIds[0];
            }
        }

        daoUtil.proxy(function(models){
            var knowledgecenter = new KnowledgeCenter();
            knowledgecenter.init(params);
            models.knowledgecenter.create(knowledgecenter.getParams(), function (err, data) {
                if (err || !data) {
                    console.log(err);
                    cb(util.getSysError());
                }else{
                    cb(null, util.getSuccessRes(data));
                }
            });
        },cb);
    },
    get:function (rowId,cb) {
        var that = this;
        daoUtil.proxy(function(models){
            models.knowledgecenter.findOne({rowId:rowId}).exec(function (err, data) {
                if (err || !data) {
                    console.log(err);
                    cb(util.getSysError());
                }else{
                    cb(null, util.getSuccessRes(data));
                }
            });
        },cb);
    },
    list: function (params, cb) {
        var query = {};
        if (params.createUid)
            query.createUid = params.createUid;
        if(params.fileType)
            query.fileType = params.fileType;
        daoUtil.proxy(function(models){
            models.knowledgecenter.find({where:query,sort:'createdAt desc'}).populate('createUid').exec(function (err, data) {
                if (err || !data) {
                    console.log(err);
                    cb(util.getSysError());
                }else{
                    cb(null, util.getSuccessRes(data));
                }
            });
        },cb);
    },
    deleteByIds:function (rowIds, cb) {
        daoUtil.proxy(function(models){
            models.knowledgecenter.destroy({rowId:rowIds}).exec(function (err, result) {
                if (err) {
                    console.log(err);
                    cb(util.getSysError());
                }else{
                    cb(null, util.getSuccessRes(result));
                }
            });
        },cb);
    }
};